//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Windows.Threading;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet.UI.Internals
{
    public class BackgroundOperation : BackgroundWorker, INotifyPropertyChanged, IDispatcherProvider //\\ remove
    {
        private readonly Dispatcher _dispatcher;

       
        private int _percentage;

        public bool Cancelled;

        public BackgroundOperation(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            ProgressChanged += backgroundOperationProgressChanged;
        }

        public Dispatcher Dispatcher
        {
            get { return _dispatcher; }
        }

        public int Percentage
        {
            get { return _percentage; }
            set
            {
                _percentage = value%100;
                notifyPropertyChanged("Percentage");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void backgroundOperationProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Percentage = e.ProgressPercentage;
        }

        private void notifyPropertyChanged(string propertyName)
        {
            Contract.Requires(GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null);

            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}